<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增组件</el-button>
        <!--        <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>-->
      </el-form-item>
      <el-form-item prop="roleName">
        <el-input v-model="queryParams.name" placeholder="请输入组件名称" clearable
                  @keyup.enter="refresh"/>
      </el-form-item>
      <el-form-item prop="labelIdList">
        <el-select v-model="state.labelIdList" multiple style="width: 200px">
          <el-option :label="item.name" :value="item.id" v-for="item of state.labelList"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="refresh">{{ $t('system.globalParam.Search') }}</el-button>
        <el-button :icon="Refresh" @click="resetQuery">{{ $t('system.globalParam.Reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <es-table class="es-table" ref="dataTableRef" :dataGetter="handleQuery"
              header-cell-class-name="app-table-head table-head-center"
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick" highlight-current-row border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="图标" align="center" prop="icons"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="标签" align="center" prop="labelIds">
        <template #default="scope">
          <el-tag type="success" v-for="item of scope.row.labelList">{{ item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="配置" align="center" prop="config"/>
      <el-table-column :label="$t('source.DataSourceConfiguration.Operation')" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.roleCode !== TENANT_ROLE_CODE">
            <!--            <el-button type="success" :icon="Operation" circle plain @click.stop="openRoleResourceDialog(scope.row)"/>-->
            <!--            <el-button type="primary" :icon="Edit" circle plain @click.stop="handleUpdate(scope.row)"/>-->
            <Edit class="operation-icon" color="#409eff" @click.stop="handleUpdate(scope.row)"/>
            <!--            <el-button type="danger" :icon="Delete" circle plain @click.stop="handleDelete(scope.row)"/>-->
            <Delete class="operation-icon" color="#409eff" @click.stop="handleDelete(scope.row)"/>
          </div>
        </template>
      </el-table-column>
    </es-table>

    <!-- 表单弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="500px"
               destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto">

        <el-form-item :label="$t('system.menu.Icon')" prop="icon">
          <!--          <SelectIcon v-model:name='formData.icon'/>-->
          <el-input v-model="formData.icons"/>
        </el-form-item>
        <el-form-item label="网站名称" prop="name">
          <el-input v-model="formData.name" placeholder="网站名称"/>
        </el-form-item>
        <el-form-item label="类型编号" prop="type">
          <el-input v-model="formData.type"/>
        </el-form-item>
        <el-form-item label="标签" prop="labelIdList">
          <el-select v-model="formData.labelIdList" multiple style="width: 200px">
            <el-option :label="item.name" :value="item.id" v-for="item of state.labelList"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea"/>
        </el-form-item>
        <el-form-item label="config" prop="config">
          <el-input v-model="formData.config" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormData">{{ $t('system.globalParam.Confirm') }}</el-button>
          <el-button @click="cancel">{{ $t('system.globalParam.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts">
export default {
  name: 'label',
};
</script>
<script setup lang="ts">
import {nextTick, onMounted, reactive, ref, toRefs, unref} from 'vue';
import {ElForm, ElMessage, ElMessageBox, ElTree} from "element-plus/es";
import {Search, Plus, Edit, Refresh, Delete, Lock, Download, Top, Operation} from '@element-plus/icons-vue';
import {TabComponentItem, TabComponentQueryParam, tabComponentService} from "@/services/resource/tabComponent";
import {tabLabelService,TabLabelItem} from "@/services/resource/tabLabel";
import EsTable from "@/components/es-table/index.vue";
import {useI18n} from 'vue-i18n'
import SelectIcon from "@/components/selectIcon/index.vue";

const {t} = useI18n()

const TENANT_ROLE_CODE = 'administrator'
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataTableRef = ref()//es-table组件

const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as TabComponentQueryParam,
  labelIdList: [] as string[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
  },
  formData: {} as TabComponentItem,
  rules: {
    roleCode: [{required: true, message: t('system.role.enterRode'), trigger: 'blur'}],
    roleDesc: [{required: true, message: t('system.role.enterDescription'), trigger: 'blur'}],
  },
  resourceDialogVisible: false,
  btnPerms: {} as any,
  labelList: [] as TabLabelItem[],
})
const {
  loading, multiple, queryParams, total, dialog, formData, rules
} = toRefs(state);

function handleAdd() {
  state.dialog = {
    title: '新增组件',
    visible: true,
  };
}

onMounted(() => {
  // 获取所有的资源
  tabLabelService.apiList({type: 4}).then(({data}) => {
    state.labelList = data;
  });
})

const handleUpdate = async (row: any) => {
  state.dialog = {
    title: '修改组件',
    visible: true,
  };
  const id: string = row.id || state.ids;
  // // 获取所有的资源
  // await listResources().then(({data}) => {
  //   resourceOptions.value = data;
  // });
  await tabComponentService.apiDetail(id).then(({data}) => {
    state.formData = data;
    state.formData.type = `${data.type}`;
  });

}

const refresh = () => {
  unref(dataTableRef).reload()
}

/**
 *  删除
 */
function handleDelete(row: any) {
  const ids = row.id
  ElMessageBox.confirm(t('system.group.dataitemDelete'), t('system.role.Warning'), {
    confirmButtonText: t('system.globalParam.Confirm'),
    cancelButtonText: t('system.globalParam.Cancel'),
    type: 'warning',
  })
      .then(() => {
        tabComponentService.apiDeleteList(ids).then(() => {
          ElMessage.success(t('system.tenant.deleteS'));
          resetQuery();
        });
      })
      .catch(() => ElMessage.info(t('system.tenant.Undeleted')));
}

function submitFormData() {
  loading.value = true;
  //菜单
  // state.formData.menuList = resourceRef.value.getCheckedNodes(false, true).map((node: any) => node.value);
  //验证
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      state.formData.labelIds = state.formData.labelIdList.join(',')
      if (state.formData.id) {
        tabComponentService.apiUpdate(state.formData.id as any, state.formData).then(() => {
          ElMessage.success(t('system.role.modifiedSuccessfully'));
          cancel();
          resetQuery();
          loading.value = false;
        });
      } else {
        tabComponentService.apiAdd(state.formData).then(() => {
          cancel();
          ElMessage.success(t('system.role.addedSuccessfully'));
          resetQuery();
          loading.value = false;
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel() {
  loading.value = false;
  dialog.value.visible = false;
  formData.value.id = undefined;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 * 查询
 */
function handleQuery(page: any) {
  if (page) {
    state.queryParams.pageNum = page.page;
    state.queryParams.pageSize = page.limit;
  }
  state.queryParams.labelIds = state.labelIdList?.join(',')
  return tabComponentService.apiListByPage(state.queryParams).then(({data}) => {
    return data
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  state.labelIdList = [];
  unref(dataTableRef).reload()
}


</script>

<style lang="scss">
.resource-tree-node {
  width: 100%;
  flex-wrap: wrap;
  display: flex;
  font-size: 14px;
  justify-content: flex-end;
  margin: 0 50px;

  .node-content {
    width: 400px;
    display: flex;
    flex-wrap: wrap;
  }

  .el-divider--vertical {
    height: 2em !important;
  }
}

.el-tree-node__content {
  height: auto !important;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;

  &:hover {
    background-color: var(--el-tree-node-hover-bg-color);
  }

  &:active {
    background-color: var(--el-tree-node-hover-bg-color);
  }
}

.el-checkbox.el-checkbox--small {
  margin: 5px;
  z-index: 999;
  background: #fff;
}
</style>
